<?php
namespace app\zjs\controller;
use app\admin\model\Customer;
use app\common\traits\WechatZjs;
use think\Controller;
use think\Facade\Session;
class Login extends Controller
{
    use WechatZjs;
    public function index()
    {
        $this->sendLogin();
    }

    /**
     *向微信服务器发起用户信息请求
     */
    protected function sendLogin()
    {
        if (!session('user_zjs')) {
            $url = url('login/receive','',true,true);
            self::getInstance()['config']->set('oauth.callback',$url);
            self::getInstance()->oauth->redirect()->send(); //发起网页授权请求
        }
    }
    /**
     *处理微信回调后处理登陆的逻辑
     */
    public function receive(){
        $oauth = self::getInstance()->oauth;//获取微信回掉回来的东西
        $user = $oauth->user()->toArray();
        foreach ($user['original'] as $key => $value) {
            $user[$key]=$value;
        }
        unset($user['original']);
        unset($user['token']);
        session('user_zjs',$user);
        $data = Customer::get(['openid'=>$user['id'],'status'=>1]);
        if(!empty($data)){
            session('user_id',$data['id']);
            session('user_attr',$data['attr']);
            session('username',$data['username']);
        }
        $this->redirect('index/index');
    }
}